<?php
/**
 * @package		简易CMS
 * @subpackage	缓存：插件
 * @version		$Id: function_importdata.php 23 2012-06-11 18:04:03Z htmambo@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2010 Hoping Software Studio.
 */

if(!defined('IN_JYCMS') || !defined('IN_ADMINCP')) {
	exit('Access Denied');
}

function import_styles($ignoreversion = 1, $dir = '', $restoreid = 0, $updatecache = 1) {
	global $_G, $importtxt, $stylearray;
	if(!isset($dir)) {
		$stylearrays = array(getimportdata('JYCMS Style'));
	} else {
		if(!$restoreid) {
			$dir = str_replace(array('/', '\\'), '', $dir);
			$templatedir = ROOT_PATH.'./template/'.$dir;
		} else {
			$templatedir = ROOT_PATH.$dir;
		}
		$searchdir = dir($templatedir);
		$stylearrays = array();
		while($searchentry = $searchdir->read()) {
			if(substr($searchentry, 0, 13) == 'jycms_style_' && fileext($searchentry) == 'xml') {
				$importfile = $templatedir.'/'.$searchentry;
				$importtxt = implode('', file($importfile));
				$stylearrays[] = getimportdata('JYCMS Style');
			}
		}
	}

	foreach((array)$stylearrays as $stylearray) {
		if(empty($ignoreversion) && strip_tags($stylearray['version']) != strip_tags($_G['setting']['version'])) {
			cpmsg('styles_import_version_invalid', '', 'error', array('cur_version' => $stylearray['version'], 'set_version' => $_G['setting']['version']));
		}

		if(!$restoreid) {
			$renamed = 0;
			if($stylearray['templateid'] != 1) {
				$templatedir = ROOT_PATH.'./'.$stylearray['directory'];
				if(!is_dir($templatedir)) {
					if(!@dmkdir($templatedir, 0777)) {
						$basedir = dirname($stylearray['directory']);
						cpmsg('styles_import_directory_invalid', '', 'error', array('basedir' => $basedir, 'directory' => $stylearray['directory']));
					}
				}

				if(!($templateid = DB::result_first("SELECT templateid FROM #__common_template WHERE name='$stylearray[tplname]'"))) {
					DB::query("INSERT INTO #__common_template (name, directory, copyright)
						VALUES ('$stylearray[tplname]', '$stylearray[directory]', '$stylearray[copyright]')");
					$templateid = DB::insert_id();
				}
			} else {
				$templateid = 1;
			}

			if(DB::result_first("SELECT COUNT(*) FROM #__common_style WHERE name='$stylearray[name]'")) {
				$stylearray['name'] .= '_'.random(4);
				$renamed = 1;
			}
			DB::query("INSERT INTO #__common_style (name, templateid)
				VALUES ('$stylearray[name]', '$templateid')");
			$styleidnew = DB::insert_id();
		} else {
			$styleidnew = $restoreid;
			DB::query("DELETE FROM #__common_stylevar WHERE styleid='$styleidnew'");
		}

		foreach((array)$stylearray['style'] as $variable => $substitute) {
			$substitute = @htmlspecialchars($substitute);
			DB::query("INSERT INTO #__common_stylevar (styleid, variable, substitute)
				VALUES ('$styleidnew', '$variable', '$substitute')");
		}
	}

	if($updatecache) {
		updatecache('styles');
		updatecache('setting');
	}
	return $renamed;
}
